
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 求小数点后的数据长度
 */
function deal(arg) {
  var t = 0;
  try {
      t = arg.toString().split(".")[1].length
  } catch(e) {}
  return t;
}

/**
 * 乘法函数，用来得到精确的乘法结果
 * @param {Object} arg1
 * @param {Object} arg2
 */
function accMul(arg1, arg2) {
  var m = 0;
  m += deal(arg1);
  m += deal(arg2);
  var r1 = Number(arg1.toString().replace(".", ""));
  var r2 = Number(arg2.toString().replace(".", ""));
  return(r1 * r2) / Math.pow(10, m)
}

/**
 * 加法函数，用来得到精确的加法结果
 * @param {Object} arg1
 * @param {Object} arg2
 */
function accAdd(arg1, arg2) {
  var r1 = deal(arg1);
  var r2 = deal(arg2);
  var m = Math.pow(10, Math.max(r1, r2))
  return(arg1 * m + arg2 * m) / m
}

/**
 * 减法函数，用来得到精确的加法结果
 * @param {Object} arg1
 * @param {Object} arg2
 */
function accSub(arg1,arg2){
  var r1 = deal(arg1);
  var r2 = deal(arg2);
  var m = Math.pow(10,Math.max(r1,r2));
  n=(r1>=r2)?r1:r2;
  return (Math.round(arg1 * m - arg2 * m) /m).toFixed(n);
}

const baseUrl = "https://xcyd.haojin.org/"

const http = (url, method, callback, data = null) => {
  var token = wx.getStorageSync('token') || null
  wx.request({
    url: baseUrl + url,
    data: data,
    method: method,
    header: {
      'content-type': 'application/json', // 默认值,
      'authorization': token
    },
    success(res) {
      if(res.header.Authorization){
        wx.setStorage({
          key:"token",
          data: res.header.Authorization
        })
      }
      if (res.statusCode == 200) {
        if (res.data) {
          if (res.data.code == 200) {
            if (res.data.current_page) {
              callback(res.data)
            } else {
              if (res.data.data) {
                callback(res.data.data)
              } else {
                callback(res.data)
              }
            }
          } else if (res.data.code == 401 || res.data.code == 403) {
            // showToast('登录过期')
            getApp().hanldelogin()
          } else {
            showToast(res.data.message)
          }
        }
      } else {
        showToast('服务器发生错误')
      }
    },
    fail(res) {
      showToast('请求失败')
    }
  })
}

const showModal = (title, callback) => {
  wx.showModal({
    title: title,
    confirmColor: "#E7211A",
    cancelColor: "#666666",
    success(res) {
      if(res.confirm){
        callback(res)
      }
    }
  })
}

const showToast = (title, icon = 'none') => {
  wx.showToast({
    title: title,
    icon: icon,
    duration: 2000
  })
}

const handleLogin = (data) => {
  var openId = wx.getStorageSync('openId') || null
  if(openId){
    http('wechat/bind/phone','POST',(res)=>{
      if(res){
        wx.setStorage({
          key:"token",
          data: res.authorization
        })
        wx.setStorage({
          key:"phone",
          data: res.phone
        })
      }
    },{
      openid:openId,
      iv:data.iv,
      encrypted_data: data.encryptedData
    })
  }
}

module.exports = {
  formatTime: formatTime,
  showModal: showModal,
  showToast: showToast,
  http: http,
  baseUrl: baseUrl,
  handleLogin: handleLogin,
  accMul:accMul,
  accAdd:accAdd,
  accSub:accSub
}